// JSON格式化模块
class JSONFormatter {
    // 格式化JSON
    static format(jsonString, indent = 2, sortKeys = false, decodeUnicode = false) {
        try {
            if (!jsonString || !jsonString.trim()) {
                return { success: false, error: 'JSON字符串不能为空' };
            }

            const parsed = JSON.parse(jsonString);

            // 如果需要排序键名
            let processedData = parsed;
            if (sortKeys) {
                processedData = this.sortObjectKeys(parsed);
            }

            let formatted = JSON.stringify(processedData, null, indent);

            // 如果需要解码Unicode
            if (decodeUnicode) {
                formatted = this.decodeUnicode(formatted);
            }

            return { success: true, data: formatted };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 解码Unicode转义序列
    static decodeUnicode(str) {
        return str.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
            return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
        });
    }

    // 递归排序对象键名
    static sortObjectKeys(obj) {
        if (obj === null || typeof obj !== 'object') {
            return obj;
        }
        
        if (Array.isArray(obj)) {
            return obj.map(item => this.sortObjectKeys(item));
        }
        
        const sortedKeys = Object.keys(obj).sort();
        const sortedObj = {};
        
        for (const key of sortedKeys) {
            sortedObj[key] = this.sortObjectKeys(obj[key]);
        }
        
        return sortedObj;
    }

    // 压缩JSON
    static compress(jsonString) {
        try {
            if (!jsonString || !jsonString.trim()) {
                return { success: false, error: 'JSON字符串不能为空' };
            }

            const parsed = JSON.parse(jsonString);
            const compressed = JSON.stringify(parsed);
            
            return { success: true, data: compressed };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 验证JSON
    static validate(jsonString) {
        try {
            if (!jsonString || !jsonString.trim()) {
                return { success: false, error: 'JSON字符串不能为空' };
            }

            JSON.parse(jsonString);
            return { success: true, data: 'JSON格式正确' };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 语法高亮
    static syntaxHighlight(json) {
        if (typeof json !== 'string') {
            json = JSON.stringify(json, null, 2);
        }

        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, 
            function (match) {
                let cls = 'json-number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'json-key';
                    } else {
                        cls = 'json-string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'json-boolean';
                } else if (/null/.test(match)) {
                    cls = 'json-null';
                }
                return '<span class="' + cls + '">' + match + '</span>';
            }
        );
    }

    // 获取友好的错误信息
    static getErrorMessage(error) {
        const message = error.message;
        
        if (message.includes('Unexpected token')) {
            if (message.includes('position')) {
                const position = message.match(/position (\d+)/);
                if (position) {
                    return `语法错误，第 ${position[1]} 个字符处有意外的符号`;
                }
            }
            return '语法错误，存在意外的符号';
        }
        
        if (message.includes('Unexpected end')) {
            return '语法错误，JSON字符串意外结束';
        }
        
        if (message.includes('Expected')) {
            return '语法错误，缺少必要的符号';
        }
        
        return message;
    }

    // 美化JSON结构分析
    static analyze(jsonString) {
        try {
            const parsed = JSON.parse(jsonString);
            const analysis = {
                type: this.getDataType(parsed),
                size: this.calculateSize(parsed),
                depth: this.calculateDepth(parsed),
                keys: this.extractKeys(parsed),
                stats: this.getStats(parsed)
            };
            
            return { success: true, data: analysis };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    static getDataType(data) {
        if (Array.isArray(data)) return 'Array';
        if (data === null) return 'null';
        return typeof data;
    }

    static calculateSize(obj, seen = new WeakSet()) {
        if (obj === null || typeof obj !== 'object') {
            return 1;
        }
        
        if (seen.has(obj)) {
            return 0; // 避免循环引用
        }
        seen.add(obj);
        
        let size = 1;
        if (Array.isArray(obj)) {
            for (const item of obj) {
                size += this.calculateSize(item, seen);
            }
        } else {
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    size += this.calculateSize(obj[key], seen);
                }
            }
        }
        
        return size;
    }

    static calculateDepth(obj, currentDepth = 0) {
        if (obj === null || typeof obj !== 'object') {
            return currentDepth;
        }
        
        let maxDepth = currentDepth;
        
        if (Array.isArray(obj)) {
            for (const item of obj) {
                maxDepth = Math.max(maxDepth, this.calculateDepth(item, currentDepth + 1));
            }
        } else {
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    maxDepth = Math.max(maxDepth, this.calculateDepth(obj[key], currentDepth + 1));
                }
            }
        }
        
        return maxDepth;
    }

    static extractKeys(obj, keys = new Set(), path = '') {
        if (obj === null || typeof obj !== 'object') {
            return keys;
        }
        
        if (Array.isArray(obj)) {
            obj.forEach((item, index) => {
                this.extractKeys(item, keys, path ? `${path}[${index}]` : `[${index}]`);
            });
        } else {
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    const currentPath = path ? `${path}.${key}` : key;
                    keys.add(currentPath);
                    this.extractKeys(obj[key], keys, currentPath);
                }
            }
        }
        
        return keys;
    }

    static getStats(obj) {
        const stats = {
            objects: 0,
            arrays: 0,
            strings: 0,
            numbers: 0,
            booleans: 0,
            nulls: 0
        };

        const traverse = (item) => {
            if (item === null) {
                stats.nulls++;
            } else if (Array.isArray(item)) {
                stats.arrays++;
                item.forEach(traverse);
            } else if (typeof item === 'object') {
                stats.objects++;
                Object.values(item).forEach(traverse);
            } else if (typeof item === 'string') {
                stats.strings++;
            } else if (typeof item === 'number') {
                stats.numbers++;
            } else if (typeof item === 'boolean') {
                stats.booleans++;
            }
        };

        traverse(obj);
        return stats;
    }

    // JSON路径查询
    static queryPath(jsonString, path) {
        try {
            const parsed = JSON.parse(jsonString);
            const pathArray = path.split('.').filter(p => p !== '');
            
            let current = parsed;
            for (const segment of pathArray) {
                if (current === null || current === undefined) {
                    return { success: false, error: `路径 ${path} 不存在` };
                }
                
                // 处理数组索引
                const arrayMatch = segment.match(/^(\w+)\[(\d+)\]$/);
                if (arrayMatch) {
                    const [, key, index] = arrayMatch;
                    current = current[key];
                    if (!Array.isArray(current)) {
                        return { success: false, error: `${key} 不是数组` };
                    }
                    current = current[parseInt(index)];
                } else {
                    current = current[segment];
                }
            }
            
            return { success: true, data: current };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 转义JSON字符串
    static escape(jsonString) {
        try {
            if (!jsonString || !jsonString.trim()) {
                return { success: false, error: 'JSON字符串不能为空' };
            }

            // 验证是否为有效JSON
            JSON.parse(jsonString);
            
            // 转义JSON字符串，使其可以作为字符串值使用
            const escaped = JSON.stringify(jsonString);
            
            return { success: true, data: escaped };
        } catch (error) {
            // 如果不是有效的JSON，直接转义字符串
            const escaped = JSON.stringify(jsonString);
            return { success: true, data: escaped };
        }
    }

    // 反转义JSON字符串
    static unescape(escapedString) {
        try {
            if (!escapedString || !escapedString.trim()) {
                return { success: false, error: '输入字符串不能为空' };
            }

            // 尝试解析转义的字符串
            const unescaped = JSON.parse(escapedString);
            
            return { success: true, data: unescaped };
        } catch (error) {
            return { success: false, error: '输入的不是有效的转义字符串' };
        }
    }

    // 转换为其他格式
    static toCSV(jsonString) {
        try {
            const parsed = JSON.parse(jsonString);
            
            if (!Array.isArray(parsed)) {
                return { success: false, error: 'JSON必须是数组格式才能转换为CSV' };
            }
            
            if (parsed.length === 0) {
                return { success: true, data: '' };
            }
            
            // 获取所有键
            const allKeys = new Set();
            parsed.forEach(item => {
                if (typeof item === 'object' && item !== null) {
                    Object.keys(item).forEach(key => allKeys.add(key));
                }
            });
            
            const keys = Array.from(allKeys);
            let csv = keys.join(',') + '\n';
            
            parsed.forEach(item => {
                const values = keys.map(key => {
                    const value = item && typeof item === 'object' ? item[key] : '';
                    if (value === null || value === undefined) return '';
                    const str = String(value);
                    return str.includes(',') || str.includes('"') || str.includes('\n') 
                        ? `"${str.replace(/"/g, '""')}"` 
                        : str;
                });
                csv += values.join(',') + '\n';
            });
            
            return { success: true, data: csv };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 转换为XML格式
    static toXML(jsonString, rootElement = 'root') {
        try {
            const parsed = JSON.parse(jsonString);
            
            const convertToXML = (obj, indent = 0) => {
                const spaces = '  '.repeat(indent);
                let xml = '';
                
                if (Array.isArray(obj)) {
                    obj.forEach((item, index) => {
                        xml += `${spaces}<item index="${index}">\n`;
                        xml += convertToXML(item, indent + 1);
                        xml += `${spaces}</item>\n`;
                    });
                } else if (typeof obj === 'object' && obj !== null) {
                    Object.keys(obj).forEach(key => {
                        const value = obj[key];
                        const safeName = key.replace(/[^a-zA-Z0-9_-]/g, '_');
                        
                        if (typeof value === 'object' && value !== null) {
                            xml += `${spaces}<${safeName}>\n`;
                            xml += convertToXML(value, indent + 1);
                            xml += `${spaces}</${safeName}>\n`;
                        } else {
                            const escapedValue = String(value)
                                .replace(/&/g, '&amp;')
                                .replace(/</g, '&lt;')
                                .replace(/>/g, '&gt;')
                                .replace(/"/g, '&quot;')
                                .replace(/'/g, '&apos;');
                            xml += `${spaces}<${safeName}>${escapedValue}</${safeName}>\n`;
                        }
                    });
                } else {
                    const escapedValue = String(obj)
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&apos;');
                    xml += `${spaces}${escapedValue}\n`;
                }
                
                return xml;
            };
            
            let xml = `<?xml version="1.0" encoding="UTF-8"?>\n<${rootElement}>\n`;
            xml += convertToXML(parsed, 1);
            xml += `</${rootElement}>`;
            
            return { success: true, data: xml };
        } catch (error) {
            return { success: false, error: this.getErrorMessage(error) };
        }
    }

    // 美化显示大小
    static formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 性能优化：大文件处理
    static formatLargeJSON(jsonString, options = {}) {
        const {
            maxSize = 1024 * 1024, // 1MB
            chunkSize = 10000,
            onProgress = null
        } = options;

        return new Promise((resolve) => {
            if (jsonString.length < maxSize) {
                // 小文件直接处理
                resolve(this.format(jsonString));
                return;
            }

            // 大文件分块处理
            let processed = 0;
            const chunks = [];
            
            const processChunk = () => {
                const end = Math.min(processed + chunkSize, jsonString.length);
                const chunk = jsonString.slice(processed, end);
                chunks.push(chunk);
                processed = end;

                if (onProgress) {
                    onProgress(processed / jsonString.length);
                }

                if (processed < jsonString.length) {
                    setTimeout(processChunk, 10); // 避免阻塞UI
                } else {
                    try {
                        const fullText = chunks.join('');
                        const result = this.format(fullText);
                        resolve(result);
                    } catch (error) {
                        resolve({ success: false, error: this.getErrorMessage(error) });
                    }
                }
            };

            processChunk();
        });
    }
}